﻿using System;
using System.Collections.Generic;
using System.Text;
using RayD.Repository.Entites.SystemModule;
using RayD.Core;
using RayD.Repository;
using Dapper;
using System.Data;
using System.Linq;
using RayD.Repository.Core;

namespace RayD.App.SystemModule
{
    public class ManaframeApp
    {

        #region 构造函数注入
        private IRepository BaseRepository;
        public ManaframeApp(IRepository repository)
        {
            this.BaseRepository = repository;
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ManaframeEntity> GetList(string queryJson)
        {
            var expression = LinqExtensions.True<ManaframeEntity>();

            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_FullName"].IsEmpty())
            {
                expression = expression.And(c => c.B_FullName.Contains(queryParam["B_FullName"].ToString()));
            }
            if (!queryParam["B_EnCode"].IsEmpty())
            {
                expression = expression.And(c => c.B_EnCode.Contains(queryParam["B_EnCode"].ToString()));
            }
            if (!queryParam["B_CreateDate"].IsEmpty())
            {
                expression = expression.And(c => c.B_CreateDate >= queryParam["B_CreateDate"][0].ToDate() && c.B_CreateDate <= queryParam["B_CreateDate"][1].ToDate());
            }
            /*关联架构*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                var manaframeIds = this.GetSubNodes(userInfo.manaframeId);
                expression = expression.And(c => manaframeIds.IndexOf(c.B_ManaframeId) >= 0);
            }
            return BaseRepository.IQueryable(expression).OrderBy(c => c.B_SortCode);
        }
        /// <summary>
        /// 获取分页列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <param name="pagination">分页参数</param>
        /// <returns></returns>
        public IEnumerable<ManaframeEntity> GetPageList(string queryJson, Pagination pagination)
        {
            var expression = LinqExtensions.True<ManaframeEntity>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_FullName"].IsEmpty())
            {
                expression = expression.And(c => c.B_FullName.Contains(queryParam["B_FullName"].ToString()));
            }
            if (!queryParam["B_EnCode"].IsEmpty())
            {
                expression = expression.And(c => c.B_EnCode.Contains(queryParam["B_EnCode"].ToString()));
            }
            if (!queryParam["B_CreateDate"].IsEmpty())
            {
                expression = expression.And(c => c.B_CreateDate >= queryParam["B_CreateDate"][0].ToDate() && c.B_CreateDate <= queryParam["B_CreateDate"][1].ToDate());
            }
            /*关联架构*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                var manaframeIds = this.GetSubNodes(userInfo.manaframeId);
                expression = expression.And(c => manaframeIds.IndexOf(c.B_ManaframeId) >= 0);
            }
            var list = this.BaseRepository.IQueryable(expression)
                        .OrderBy(pagination.sidx, pagination.sord)
                        .ToTree();
            /***********************分页处理*********************/
            var rowsData = list.Skip(pagination.pageSize * (pagination.currentPage - 1)).Take(pagination.pageSize);
            pagination.records = list.Count();

            return rowsData;
        }
        /// <summary>
        /// 获取组织本身和子组织的id
        /// </summary>
        /// <param name="parentId">父级ID</param>
        /// <returns></returns>
        [Caching]
        public virtual List<string> GetSubNodes(string B_ParentId)
        {
            if (B_ParentId.IsEmpty())
            {
                return new List<string>();
            }
            List<string> res = new List<string>();
            res.Add(B_ParentId);

            var expression = LinqExtensions.True<ManaframeEntity>();
            var list = BaseRepository
                .IQueryable(expression)
                .OrderBy(c => c.B_SortCode);
            list.ToTree(B_ParentId).GetSubNodes(res);
            return res;
        }
        /// <summary>
        /// 获取当前用户所属组织及其下级组织树型列表数据
        /// </summary>
        /// <param name="account">登录账户(缓存键)</param>
        /// <returns></returns>
        [Caching]
        public virtual List<ManaframeEntity> GetTreeList(string account)
        {
            var expression = LinqExtensions.True<ManaframeEntity>();
            /*关联架构*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                var manaframeIds = this.GetSubNodes(userInfo.manaframeId);
                expression = expression.And(c => manaframeIds.IndexOf(c.B_ManaframeId) >= 0);
            }
            return this.BaseRepository
                .IQueryable(expression)
                .OrderBy(c => c.B_SortCode)
                .ToTree()
                .ToList();
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存实体(新增,编辑)
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) SaveForm(ManaframeEntity formEntity)
        {
            /*关联架构*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem && formEntity.B_ParentId.IsEmpty())
            {
                return (false, "非超管用户，所属组织必填！");
            }
            //字段验重
            if (ValidateExist(formEntity.B_ManaframeId, "B_FullName", formEntity.B_FullName)) return (false, "组织名称已存在！");
            if (ValidateExist(formEntity.B_ManaframeId, "B_EnCode", formEntity.B_EnCode)) return (false, "组织编码已存在！");
            if (!formEntity.B_ManaframeId.IsEmpty())
            {
                //编辑(Null、主键不会更改)
                formEntity.Modify();
                this.BaseRepository.Update(formEntity);
            }
            else
            {
                //新增
                formEntity.Create();
                this.BaseRepository.Insert(formEntity);
            }
            return (true, "保存成功！");
        }
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) DeleteForm(ManaframeEntity formEntity)
        {
            this.BaseRepository.Delete(formEntity);
            return (true, "删除成功！");
        }
        #endregion

        #region 数据验证
        /// <summary>
        /// 验证字段值是否存在
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="field">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public bool ValidateExist(string id, string field, string value)
        {
            var expression = LinqExtensions.True<ManaframeEntity>();
            if (!string.IsNullOrEmpty(id))
            {
                expression = expression.And(t => t.B_ManaframeId != id);
            }
            return this.BaseRepository.IQueryable(expression).Exist(field, value);
        }
        #endregion
    }
}
